package m

import (
	"GameServer/Common/data"
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"
	"fmt"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"
)

// 当前激活活动Single
type ActActivityInfo struct {
	BaseM
	Id           bson.ObjectId `bson:"_id" json:"_id"`
	ActId        int64         `bson:"actId"`        // 活动id
	TypeEnum     int64         `bson:"typeEnum"`     // 活动类型
	BeginTime    int64         `bson:"beginTime"`    // 开始时间
	EndTime      int64         `bson:"endTime"`      // 结束时间
	ResetMonth   int64         `bson:"resetMonth"`   // 按月重置 0-不设置 1-按月重置
	ResetWeekDay int64         `bson:"resetWeekDay"` // 周重置-周几重置
}

func NewActActivityInfo() cache.EntryI {
	var value cache.EntryI = new(ActActivityInfo)
	return value
}

func (u *ActActivityInfo) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("actActivityGroup", bson.M{"_id": u.Id}, u)
	if err != nil {
		return
	}
	return
}

func (u *ActActivityInfo) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		u.Id = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		u.Id = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "ActActivityInfo_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return u.LoadData()
}

//加载数据
func (u *ActActivityInfo) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("actActivityGroup", bson.M{"_id": u.Id}, nil, &u)
	if err != nil {
		if err.Error() == "not found" {
			err = errors.NewErrcode(data.Errcode.NotFound, fmt.Sprintf("没有找到活动信息. id:%s", u.Id.Hex()))
			return nil
		}
		return
	}
	return
}

//更新数据
func (u *ActActivityInfo) Update(val *ActActivityInfo) {
	Cache.Put("actActivityGroup", u.Id.Hex(), val)
	val.UpdateData()
}

func (u *ActActivityInfo) Delete() (err error) {
	Cache.Remove("actActivityGroup", u.Id.Hex())
	return dbmodule.MgoDB.GameDB.Remove("actActivityGroup", bson.M{"_id": u.Id})
}

func (u *ActActivityInfo) UpsetAndUpdate(val *ActActivityInfo) {
	u = val
	u.Update(u)
	return
}
